package com.xauto.pioneer.appuser.activity.takeCar;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.mapapi.utils.OpenClientUtil;
import com.baidu.mapapi.utils.route.BaiduMapRoutePlan;
import com.baidu.mapapi.utils.route.RouteParaOption;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.xauto.pioneer.appuser.MainActivity;
import com.xauto.pioneer.appuser.MyApplication;
import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.BaseActivity;
import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.Constants;
import com.xauto.pioneer.appuser.http.LHttpLib;
import com.xauto.pioneer.appuser.interfaces.CarOrderInfoCallBack;
import com.xauto.pioneer.appuser.interfaces.CommonCallBack;
import com.xauto.pioneer.appuser.model.CarOrderInfo;
import com.xauto.pioneer.appuser.model.ClientSetting;
import com.xauto.pioneer.appuser.model.DamageImageInfo;
import com.xauto.pioneer.appuser.model.JSONStatus;
import com.xauto.pioneer.appuser.model.PageInfo;
import com.xauto.pioneer.appuser.model.ParkingSite;
import com.xauto.pioneer.appuser.util.DataLoadUtil;
import com.xauto.pioneer.appuser.util.OverlayManager;
import com.xauto.pioneer.appuser.util.PreferencesUtils;
import com.xauto.pioneer.appuser.util.ViewUtil;
import com.xauto.pioneer.appuser.view.PromptDialog;
import com.xauto.pioneer.appuser.view.TopBar;

import net.tsz.afinal.FinalDb;

import org.json.JSONArray;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Created by lsx on 2018-03-10.
 */

public class FoundCarActivity extends BaseActivity {

    @Bind(R.id.topBar)
    TopBar topBar;
    @Bind(R.id.mapMain)
    MapView mMapView;
    @Bind(R.id.park_distance_text)
    TextView parkDistanceText;
    @Bind(R.id.park_time_text)
    TextView parkTimeText;
    @Bind(R.id.park_website_text)
    TextView parkWebsiteText;
    @Bind(R.id.park_num_text)
    TextView parkNumText;
    @Bind(R.id.park_info_linear)
    View parkInfoLinear;
    @Bind(R.id.ac_main)
    RelativeLayout acMain;
    @Bind(R.id.open_car_text)
    TextView openCarText;
    @Bind(R.id.close_car_text)
    TextView closeCarText;
    @Bind(R.id.find_car_text)
    TextView findCarText;
    @Bind(R.id.cancel_order_text)
    TextView cancelOrderText;
    @Bind(R.id.operateLinear)
    LinearLayout operateLinear;
    @Bind(R.id.return_car_text)
    TextView returnCarText;
    @Bind(R.id.using_car_mileage_text)
    TextView usingCarMileageText;
    @Bind(R.id.using_car_time_text)
    TextView using_car_time_text;
    @Bind(R.id.using_car_cost_text)
    TextView usingCarCostText;
    @Bind(R.id.using_car_credit_text)
    TextView usingCarCreditText;
    @Bind(R.id.using_car_model_text)
    TextView usingCarModelText;
    @Bind(R.id.using_car_color_text)
    TextView usingCarColorText;
    @Bind(R.id.using_car_info_linear)
    View usingCarInfoLinear;
    @Bind(R.id.self_serve_text)
    TextView selfServeText;
    @Bind(R.id.return_car_linear)
    LinearLayout returnCarLinear;
    @Bind(R.id.bottomLinear)
    LinearLayout bottomLinear;
    @Bind(R.id.show_view_linear)
    LinearLayout showViewLinear;
    @Bind(R.id.show_view_img)
    ImageView showViewImg;
    @Bind(R.id.location_image)
    ImageView locationImage;
    //订单运行中车辆控制按钮
    @Bind(R.id.OrderRun_open_car)
    TextView OrderRun_open_car;
    @Bind(R.id.OrderRun_close_car)
    TextView OrderRun_close_car;
    @Bind(R.id.OrderRun_whistle_car)
    TextView OrderRun_whistle_car;
    @Bind(R.id.ivMainRoadStatus)
    ImageView ivMainRoadStatus;
    @Bind(R.id.ivChat)
    ImageView ivChat;
    @Bind(R.id.ivShowCar)
    ImageView ivShowCar;
    @Bind(R.id.find_car_exception)
    TextView find_car_exception;
    //    @Bind(R.id.OverCarButton)
//    LinearLayout OverCarButton;
    private PromptDialog promptDialog;
    String plateNo = "";
    String carOrderNo = "";
    boolean createdOrder = false;
    List<DamageImageInfo> updateServerPhotos;
    private boolean isHintTopView = true;
    /****************
     * 地图相关
     ******************/
    private BaiduMap mBaiDuMap;
    /**
     * 定位相关
     */
    private LocationClient mLocClient;
    boolean isFirstLoc = true; // 是否首次定位
    /**
     * 所有marker集合
     */
    private List<OverlayOptions> overlayOptionsList;
    /**
     * marker 操作管理
     */
    private MyOverlayManager myOverlayManager;
    /**
     * 定位成功后，返回的当前定位
     */
    private BDLocation bdLocation=null;
    private LatLng currentLatLng;
    private boolean isOpenRoadStatus = false;
    /**当前地图左右距离*/
    private int currentDistance = 200000;
    /**返回所有取车列表*/
    private int currentDistanceAll =200000;
    //当前车辆订单信息
    CarOrderInfo currentCarOrderInfo = null;
    private float currentZoom = 18;
    /**
     * 还车网点集合
     */
    private List<ParkingSite> parkingSiteList;
    /**
     * 还车网点标注集合
     */
    private List<ParkingSite> parkingMarkerList;
    private DisplayImageOptions hasCarOptions;
    private DisplayImageOptions noCarOptions;
    private int TIME=3000;
//    private MyThread thread;
    /**判断是否已经开始订单*/
    public static int Order=0;
    /**判断是否点击拍照*/
    public static int OrderPhoto=0;
    public static int ParkingStat=0;
    String telNumber="";
    /**车辆位置*/
    LatLng  CarLatLng=null;
    BitmapDescriptor Carbitmap = BitmapDescriptorFactory.fromResource(R.mipmap.ic_map_car_red);
    MarkerOptions  CarmarkerOptions;
    Marker CarMaker;
    /**
     * 入口
     *
     * @param mContext
     */
    public static void startAction(Context mContext, String plateNo, String carOrderNo, boolean createdOrder) {
        Intent intent = new Intent(mContext, FoundCarActivity.class);
        intent.putExtra("plateNo", plateNo);
        intent.putExtra("carOrderNo", carOrderNo);
        intent.putExtra("createdOrder", createdOrder);
        mContext.startActivity(intent);
    }

    @Override
    protected int getContentView() {
        return R.layout.ac_found_car;
    }

    @Override
    protected void initView() {
        //注册EventBus
        EventBus.getDefault().register(this);
        promptDialog = new PromptDialog(mContext, getString(R.string.notice), getString(R.string.text_not_network),
                getString(R.string.to_setting), getString(R.string.logout), getString(R.string.dialogpic_notice),new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //去设置
                promptDialog.dismiss();
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //退出
                promptDialog.dismiss();
            }
        });
    }

    @Override
    protected void initData() {
        hasCarOptions = MyApplication.getDisplayImageOptions(mContext, 20, R.mipmap.ic_map_car_gray1);
        noCarOptions = MyApplication.getDisplayImageOptions(mContext, 20, R.mipmap.ic_map_car_blue1);

        plateNo = getIntent().getStringExtra("plateNo");
        carOrderNo = getIntent().getStringExtra("carOrderNo");
        createdOrder = getIntent().getBooleanExtra("createdOrder",false);
        ivMainRoadStatus.setImageResource(isOpenRoadStatus ? R.mipmap.ic_map_road_status : R.mipmap.ic_map_road_status_gray);
        initTelNumber();
        topBar.showView(TopBar.LEFT_IMAGE_BTN, TopBar.TITLE, TopBar.RIGHT_TV_BTN);
        topBar.setText(TopBar.TITLE, plateNo);
        topBar.setText(TopBar.RIGHT_TV_BTN, "跳转导航");
        topBar.setImage(TopBar.LEFT_IMAGE_BTN, R.mipmap.ic_common_left);
        topBar.setLeftOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                backEvent();
            }
        });
        topBar.setRightOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //WebViewActivity.startAction(mContext, 6);
                setMap(bdLocation,currentCarOrderInfo.parking_site_info.latitude_num,currentCarOrderInfo.parking_site_info.longitude_num);
            }
        });
        startRefreshData();
        initBaiDuMap();
    }
    private void initTelNumber(){
        FinalDb finalDb = FinalDb.create(mContext);
        List<ClientSetting> client = finalDb.findAll(ClientSetting.class);
        if (client != null && client.size() >0){
            telNumber = client.get(client.size()- 1).getContact_number();
        }
    }
    /**
     * 显示相关数据
     *
     * @param carOrderInfo
     */
    private void showDataToView(final CarOrderInfo carOrderInfo) {
        //显示标题
        topBar.setText(TopBar.TITLE, carOrderInfo.carInfo.plate_no);
        //显示界面顶部停车场信息
        parkInfoLinear.setVisibility(View.VISIBLE);
        double distance = 0d;
        java.text.DecimalFormat   df=new   java.text.DecimalFormat("#.00");
        try {
            //计算当前位置到网点距离
            distance = DistanceUtil.getDistance(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()), new LatLng(carOrderInfo.parking_site_info.latitude_num, carOrderInfo.parking_site_info.longitude_num));
        } catch (Exception e) {

        }
        //取车点距离
        parkDistanceText.setText(String.format(getString(R.string.park_distance),df.format(distance) + ""));
        //取车剩余时间
        final int[] reserve_remind_time = {0};
        try {
            reserve_remind_time[0] = Integer.parseInt(carOrderInfo.reserveInfo.reserve_remind_time);
        } catch (Exception e) {

        }
//        final Timer timer2 = new Timer();
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        reserve_remind_time[0]--;
//                        if (reserve_remind_time[0] >= 0) {
//                            parkTimeText.setText(String.format(getString(R.string.park_time), (reserve_remind_time[0] / 60) + ""));
//                        } else {
//                            //预约时间到达 取消倒计时
//                            parkTimeText.setText(String.format(getString(R.string.park_time), "0"));
//                            timer2.cancel();
//                        }
//                    }
//                });
//            }
//        }, 0, 1000);
        //取车网点
        parkWebsiteText.setText(String.format(getString(R.string.park_website), carOrderInfo.parking_site_info.parking_site_name));
        //车位号
        parkNumText.setText(String.format(getString(R.string.park_num), carOrderInfo.parking_site_info.parking_site_no));
       /* //已行驶
        usingCarMileageText.setText(getString(R.string.using_car_mileage,carOrderInfo.billing_charge_info.kilometre,"",""));
        //当前费用
        usingCarCostText.setText(getString(R.string.using_car_cost,String.valueOf(Integer.parseInt(carOrderInfo.billing_charge_info.total_kilometre)+Integer.parseInt(carOrderInfo.billing_charge_info.total_run_time))));
        //信用额度
        usingCarCreditText.setText(getString(R.string.using_car_credit,carOrderInfo.member_info.member_account_info));*/
        //车辆型号
        usingCarModelText.setText(getString(R.string.using_car_model, carOrderInfo.carInfo.car_series_name));
        //车辆颜色
        usingCarColorText.setText(getString(R.string.using_car_color, carOrderInfo.carInfo.car_color_name));
        if (createdOrder)startUseCar();

        //订单状态是21则隐藏返回键
        if ("21".equals(carOrderInfo.car_order_status_id)){
            topBar.hideView(TopBar.LEFT_IMAGE_BTN);
        }else {
            topBar.showView(TopBar.LEFT_IMAGE_BTN);
        }

    }

    /***
     * 显示车辆位置
     */

    public void showCarPosition(){
        if(CarMaker==null){
            CarLatLng = new LatLng(Double.valueOf(currentCarOrderInfo.carInfo.car_latitude),Double.valueOf(currentCarOrderInfo.carInfo.car_longitude));
            CarmarkerOptions = new MarkerOptions().icon(Carbitmap).position(CarLatLng);
            CarMaker = (Marker)mBaiDuMap.addOverlay(CarmarkerOptions);}
        else{
            CarMaker.remove();
            CarLatLng = new LatLng(Double.valueOf(currentCarOrderInfo.carInfo.car_latitude),Double.valueOf(currentCarOrderInfo.carInfo.car_longitude));
            CarmarkerOptions = new MarkerOptions().icon(Carbitmap).position(CarLatLng);
            CarMaker = (Marker)mBaiDuMap.addOverlay(CarmarkerOptions);
        }
        setMyLocationToCenter(new LatLng(Double.valueOf(currentCarOrderInfo.carInfo.car_latitude),Double.valueOf(currentCarOrderInfo.carInfo.car_longitude)));
    }

    /**
     * 订单运行中显示金额
     * */
    public void showDataToViewOrderRun(CarOrderInfo carOrderInfo) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(currentCarOrderInfo!=null){
                    if(currentCarOrderInfo.billing_charge_info!=null){
                        //已行驶公里
                        usingCarMileageText.setText(getString(R.string.using_car_mileage,currentCarOrderInfo.billing_charge_info.kilometre));
                        //已行驶时间
                        using_car_time_text.setText(getString(R.string.using_car_time,currentCarOrderInfo.billing_charge_info.run_time));
                        //当前费用
                        usingCarCostText.setText(getString(R.string.using_car_cost,currentCarOrderInfo.total_amount ));

                    }}
            }
        });
        //信用额度
        // usingCarCreditText.setText(getString(R.string.using_car_credit,DataLoadUtil.total_credit_amount.toString()));
        usingCarCreditText.setVisibility(View.GONE);
        //车辆型号
        usingCarModelText.setText(getString(R.string.using_car_model, currentCarOrderInfo.carInfo.car_series_name));
        //车辆颜色
        usingCarColorText.setText(getString(R.string.using_car_color, currentCarOrderInfo.carInfo.car_color_name));


        //订单状态是21则隐藏返回键
        if ("21".equals(carOrderInfo.car_order_status_id)){
            Order=1;
            DataLoadUtil.getCarOrderDetailOrderRun(true,mContext, carOrderNo, new CarOrderInfoCallBack() {
                @Override
                public void getCarOrderInfo(CarOrderInfo carOrderInfo) {
                    currentCarOrderInfo = carOrderInfo;
                }
            });
            topBar.hideView(TopBar.LEFT_IMAGE_BTN);
        }else {
            topBar.showView(TopBar.LEFT_IMAGE_BTN);
        }

    }

    @OnClick({R.id.open_car_text,R.id.find_car_exception,R.id.close_car_text, R.id.find_car_text,
            R.id.cancel_order_text, R.id.return_car_text, R.id.self_serve_text,R.id.show_view_order,
            R.id.location_image,R.id.OrderRun_open_car,R.id.OrderRun_close_car,R.id.OrderRun_whistle_car,
            R.id.ivMainRoadStatus,R.id.ivShowCar,R.id.ivChat})
    public void onViewClicked(View view){
        switch(view.getId()) {
            case R.id.open_car_text:

                //车辆拍照
                GetMemberToCar();
                break;
            case R.id.find_car_exception:
                //异常处理
                Intent intent = new Intent(mContext, TakePhotoFeedbackActivity.class);
                intent.putExtra("car_no", carOrderNo);
                intent.putExtra("longitude", String.valueOf(bdLocation.getLongitude()));
                intent.putExtra("latitude", String.valueOf(bdLocation.getLatitude()));
                intent.putExtra("address", String.valueOf(bdLocation.getAddrStr()));
                intent.putExtra("Route", String.valueOf(bdLocation.getAddrStr()));
                intent.putExtra("status", "1");
                startActivityForResult(intent, 202);
                break;
            case R.id.close_car_text:
                //关闭车辆
                operateCar("2", false,bdLocation);
                break;
            case R.id.find_car_text:
                //鸣笛找车
                operateCar("3", false,bdLocation);
                break;
            case R.id.cancel_order_text:
                //取消订单
                //获取车辆订单信息
                //operateCar("1",false);
                DataLoadUtil.getCarOrderDetailOrderRun(true,mContext, carOrderNo,  new CarOrderInfoCallBack() {
                    @Override
                    public void getCarOrderInfo(final CarOrderInfo carOrderInfo) {
                        Log.e("tag","carorderinfo = "+ carOrderInfo.toString());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                currentCarOrderInfo = carOrderInfo;
                                if ("11".equals(carOrderInfo.car_order_status_id)) {
                                    cancelOrderEvent(carOrderInfo);
                                } else {
//                                   Order=1;
                                    DataLoadUtil.getCarOrderDetailOrderRun(true,mContext, carOrderNo, new CarOrderInfoCallBack() {
                                        @Override
                                        public void getCarOrderInfo(CarOrderInfo carOrderInfo) {
                                            currentCarOrderInfo = carOrderInfo;
                                        }
                                    });
                                    prompt("此订单正在使用进行中，暂不能取消！");
                                }

                            }
                        });
                    }
                });
                break;
            case R.id.return_car_text:
                //申请还车
                //applyReturnCar();
                if(PreferencesUtils.getString(mContext,"Park_NO").equals("0")||PreferencesUtils.getString(mContext,"Park_NO").equals("")){
                    //附近网点还车
                    Intent intent2 = new Intent(mContext, ParkingSpaceActivity.class);
                    intent2.putExtra("car_order_no", carOrderNo);
                    intent2.putExtra("parking_site_no", currentCarOrderInfo.parking_site_info.parking_site_no);
                    intent2.putExtra("longitude_num", String.valueOf(bdLocation.getLongitude()));
                    intent2.putExtra("latitude_num", String.valueOf(bdLocation.getLatitude()));
                    intent2.putExtra("distance_range", currentDistanceAll);
                    startActivityForResult(intent2, 200);
                }else{
                    applyReturnCar2();
                }
                break;
            case R.id.self_serve_text:
                // 自助加油
                RefuelActivity.startAction(mContext, carOrderNo);
                break;
            case R.id.show_view_order:
                //显示，隐藏顶部视图
                isHintTopView = !isHintTopView;
                showViewLinear.setVisibility(isHintTopView ? View.GONE : View.VISIBLE);
                showViewImg.setImageResource(isHintTopView ? R.mipmap.xiala : R.mipmap.shouqi);
                break;
            case R.id.location_image:
                //回归到我的位置
                setMyLocationToCenter(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()));
                currentLatLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                if (Order == 1) {
                    mBaiDuMap.clear();
                   load();
                }
                if (Order == 0) {
                   loadGetCar();
                }
                break;
            case R.id.OrderRun_open_car:
                //订单运行中开车门
                operateCar("1", false,bdLocation);
                break;
            case R.id.OrderRun_close_car:
                //订单运行中关车门
                operateCar("2", false,bdLocation);
                break;
            case R.id.OrderRun_whistle_car:
                //订单运行中车辆鸣笛
                operateCar("3", false,bdLocation);
                break;
            case R.id.ivShowCar:
                showCarPosition();
                break;
            case R.id.ivChat:
                //用intent启动拨打电话
                Intent intent2 = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+telNumber));
                startActivity(intent2);
                break;
            case R.id.ivMainRoadStatus:
                //打开路况信息
                isOpenRoadStatus = !isOpenRoadStatus;
                ivMainRoadStatus.setImageResource(isOpenRoadStatus ? R.mipmap.ic_map_road_status : R.mipmap.ic_map_road_status_gray);
                // 开启交通图
                mBaiDuMap.setTrafficEnabled(isOpenRoadStatus);
                break;
        }
    }

    /**
     * 设置我的位置到中心点
     */
    private void setMyLocationToCenter(LatLng latLng){
        //设置当前位置到地图中间
        MapStatus mapStatus = new MapStatus.Builder().target(latLng).zoom(currentZoom).build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);
        mBaiDuMap.setMapStatus(mMapStatusUpdate);
    }
    private class MyOverlayManager extends OverlayManager {

        private List<OverlayOptions> overlayOptionsList;

        public void setOverlayOptionsList(List<OverlayOptions> overlayOptionsList) {
            this.overlayOptionsList = overlayOptionsList;
        }

        public MyOverlayManager(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public List<OverlayOptions> getOverlayOptions() {
            return overlayOptionsList;
        }

        @Override
        public boolean onMarkerClick(Marker marker) {
            return false;
        }

        @Override
        public boolean onPolylineClick(Polyline polyline) {
            return false;
        }
    }
    /************************************** 百度地图相关配置 ⬆️ *******************************************/
    /**
     * 初始化地图
     */
    private void initBaiDuMap() {
        mBaiDuMap = mMapView.getMap();
//        UiSettings mUiSettings=mBaiDuMap.getUiSettings();
//        mUiSettings.setCompassEnabled(true);
        //初始化默认西安中心点坐标
        Double lat = 34.2777998978;
        Double lng = 108.953098279;
        LatLng latLng = new LatLng(lat, lng);
        setMyLocationToCenter(latLng);

        // LocationMode.COMPASS 罗盘 FOLLOWING 跟随 NORMAL 普通
//        mBaiDuMap.setMyLocationConfigeration(
////        new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, null, accuracyCircleFillColor, accuracyCircleStrokeColor));
//                new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, null)); //传入null当前定位是默认蓝色小点图标
        // 开启定位图层
        mBaiDuMap.setMyLocationEnabled(true);
        // 开启交通路况图
        // mBaiDuMap.setTrafficEnabled(isOpenRoadStatus);
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.start();
        mLocClient.registerLocationListener(new MyLocationListener());
        initLocation();
        myOverlayManager = new MyOverlayManager(mBaiDuMap);
        mBaiDuMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                //点击地图标注
                /*Bundle info = marker.getExtraInfo();
                ParkingSite parkingSite = (ParkingSite) info.getSerializable("parkingSite");
                returnCarToWebsite(parkingSite);*/
                return true;
            }
        });
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            bdLocation = location;
            PreferencesUtils.putString(mContext,"ADR",String.valueOf(bdLocation.getAddrStr()));
            currentLatLng = new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());
//            if (location.getLocType() == BDLocation.TypeNetWorkLocation) {

//            }
            // 构造定位数据
            MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude()).longitude(location.getLongitude()).build();
            mBaiDuMap.setMyLocationData(locData); // 设置定位数据
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18);
                mBaiDuMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
            if(Order==0){
                loadGetCar();
            }
            mBaiDuMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
                @Override
                public void onMapLoaded() {
                    myOverlayManager = new MyOverlayManager(mBaiDuMap);
                }
            });

        }
        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    /**
     * 初始化定位设置
     */
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系
        int span = 0;//1000 //todo 根据实际情况是否关闭定位，暂时只定位一次
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setScanSpan(span);
        //可选，设置是否需要地址信息，默认不需要
        option.setIsNeedAddress(true);
        //可选，默认false,设置是否使用gps
        option.setOpenGps(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setLocationNotify(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIsNeedLocationPoiList(true);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.setIgnoreKillProcess(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集
        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        option.setEnableSimulateGps(false);
        // 在网络定位中，获取手机机头所指的方向
        option.setNeedDeviceDirect(true);
        mLocClient.setLocOption(option);
    }
    /**
     * 地图取车网点打点
     */
    void addGetCarMarker() {
        if(currentCarOrderInfo!=null){
            final View v = LayoutInflater.from(this).inflate(R.layout.item_parking_space_marker, null);
            final ImageView ivMapParkingSite = (ImageView) v.findViewById(R.id.ivMapParkingSite);
            TextView tvMapUsableCarCount = (TextView) v.findViewById(R.id.tvMapUsableCarCount);
            TextView tvMapUsableCarCountName = (TextView) v.findViewById(R.id.tvMapUsableCarCountName);
            tvMapUsableCarCount.setVisibility(View.GONE);
            tvMapUsableCarCountName.setVisibility(View.GONE);
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(new LatLng(currentCarOrderInfo.parking_site_info.latitude_num, currentCarOrderInfo.parking_site_info.longitude_num));
            markerOptions.icon(BitmapDescriptorFactory.fromView(v));
            Bitmap bitmap = ImageLoader.getInstance().loadImageSync(currentCarOrderInfo.parking_site_info.parking_site_image.source);
            ivMapParkingSite.setImageBitmap(bitmap);
            overlayOptionsList = new ArrayList<>();
            overlayOptionsList.add(markerOptions);
            myOverlayManager.removeFromMap();
            myOverlayManager.setOverlayOptionsList(overlayOptionsList);
            myOverlayManager.addToMap();
            myOverlayManager.zoomToSpan();}
        setMyLocationToCenter(currentLatLng);
    }

    /**
     * 地图打点
     */
    void addMarker() {
//        for (int i = 0; i < parkingSiteList.size(); i++) {
        if (parkingMarkerList == null || parkingMarkerList.size() == 0){
            if (overlayOptionsList != null && overlayOptionsList.size() > 0) {
                if (!overlayOptionsList.equals(myOverlayManager.getOverlayOptions())) {
                    myOverlayManager.removeFromMap();
                    myOverlayManager.setOverlayOptionsList(overlayOptionsList);
                    myOverlayManager.addToMap();
                    myOverlayManager.zoomToSpan();
                }
            }
            setMyLocationToCenter(currentLatLng);
            return;
        }
        final ParkingSite parkingSite = parkingMarkerList.get(0);
        final View v = LayoutInflater.from(this).inflate(R.layout.item_parking_space_marker, null);
        final ImageView ivMapParkingSite = (ImageView) v.findViewById(R.id.ivMapParkingSite);
        TextView tvMapUsableCarCount = (TextView) v.findViewById(R.id.tvMapUsableCarCount);
        TextView tvMapUsableCarCountName = (TextView) v.findViewById(R.id.tvMapUsableCarCountName);
        tvMapUsableCarCount.setText(parkingSite.usable_space_count + "");
        tvMapUsableCarCountName.setText(parkingSite.parking_site_name + "," +parkingSite.usable_space_count+ "车位");
        // if (StringUtils.isEmpty(parkingSite.parking_site_image.thumb)){
        if (parkingSite.parking_site_image==null){
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(new LatLng(parkingSite.latitude_num, parkingSite.longitude_num));
            markerOptions.icon(BitmapDescriptorFactory.fromView(v));
            Bundle info = new Bundle();
            info.putSerializable("parkingSite", parkingSite);
            markerOptions.extraInfo(info);
            overlayOptionsList.add(markerOptions);
            if (parkingMarkerList.size() >0)parkingMarkerList.remove(0);
        }else {
            imageLoader.displayImage(parkingSite.parking_site_image.thumb, ivMapParkingSite,
                    parkingSite.usable_car_count > 0 ? hasCarOptions : noCarOptions, new ImageLoadingListener() {
                        @Override
                        public void onLoadingStarted(String s, View view) {

                        }

                        @Override
                        public void onLoadingFailed(String s, View view, FailReason failReason) {
                            MarkerOptions markerOptions = new MarkerOptions();
                            markerOptions.position(new LatLng(parkingSite.latitude_num, parkingSite.longitude_num));
                            markerOptions.icon(BitmapDescriptorFactory.fromView(v));
                            Bundle info = new Bundle();
                            info.putSerializable("parkingSite", parkingSite);
                            markerOptions.extraInfo(info);
                            overlayOptionsList.add(markerOptions);
                            if (parkingMarkerList.size() >0)parkingMarkerList.remove(0);
                        }

                        @Override
                        public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                            MarkerOptions markerOptions = new MarkerOptions();
                            markerOptions.position(new LatLng(parkingSite.latitude_num, parkingSite.longitude_num));
                            markerOptions.icon(BitmapDescriptorFactory.fromView(v));
                            Bundle info = new Bundle();
                            info.putSerializable("parkingSite", parkingSite);
                            markerOptions.extraInfo(info);
                            ivMapParkingSite.setImageBitmap(bitmap);
                            overlayOptionsList.add(markerOptions);
                            if (parkingMarkerList.size() >0)parkingMarkerList.remove(0);
                        }

                        @Override
                        public void onLoadingCancelled(String s, View view) {

                        }
                    });

//            }
        }

    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        if(mBaiDuMap!=null){
            mBaiDuMap.clear();}
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        DataLoadUtil.getCarOrderDetailOrderRun(true,mContext, carOrderNo, new CarOrderInfoCallBack() {
            @Override
            public void getCarOrderInfo(CarOrderInfo carOrderInfo) {
                currentCarOrderInfo = carOrderInfo;
                if(carOrderInfo.car_order_status_id.equals("21")){
                    startUseCar();
                }
            }
        });
        super.onResume();
    }

    /*@Override
    protected void onStop() {
        super.onStop();
        mBaiDuMap.setMyLocationEnabled(false);
        mLocClient.stop();
    }*/

    @Override
    protected void onDestroy() {//反注册EventBus
        EventBus.getDefault().unregister(this);
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiDuMap.setMyLocationEnabled(false);
        mBaiDuMap.clear();
        mMapView.onDestroy();
        mMapView = null;
        mBaiDuMap = null;
        stopTimer();
//        if (thread != null) {
//            thread.stop = true;
//            thread = null;
//        }
        Order=0;
        super.onDestroy();
        PreferencesUtils.putString(mContext,"Park_NO","0");
    }
    /**停止刷新数据*/
    private void stopTimer(){
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //无效
        if (keyCode == event.KEYCODE_HOME) {
            backEvent();
            return true;
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            //处理返回按键
            backEvent();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 返回事件
     */
    private void backEvent(){
        DataLoadUtil.getCarOrderDetailOrderRun(true,mContext, carOrderNo, new CarOrderInfoCallBack() {
            @Override
            public void getCarOrderInfo(final CarOrderInfo carOrderInfo) {
                //        11	预约进行中	预约进行中	0	预约中
                //        12	预约已取消	预约已取消	1	已取消
                //        13	预约取消违约待支付	预约取消违约待支付	1	待支付
                //        14	预约取消违约已支付	预约取消违约已支付	1	已支付
                //        21	正常使用进行中	正常使用进行中	0	使用中
                //        22	正常使用完成待支付	正常使用完成待支付	1	待支付
                //        23	正常使用完成已支付	正常使用完成已支付	1	已支付
                //        31	异常使用关闭待支付	异常使用关闭待支付	1	待支付
                //        32	异常使用关闭已支付	异常使用关闭已支付	1	已支付
                //        41	后台关闭	后台关闭	1	已关闭
                //        24	正常使用完成等待中	正常使用完成等待中	1	计算中
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        currentCarOrderInfo = carOrderInfo;
                        String orderStatusId = carOrderInfo.car_order_status_id;
                        if ("21".equals(orderStatusId)){
                            prompt("此订单正在使用进行中，暂不能取消！");
                        }else if ("11".equals(orderStatusId)){
                            cancelOrderEvent(carOrderInfo);
                        }else {
                            onBackPressed();
                        }
                    }
                });
            }
        });
    }
    /**
     * 取消订单时间
     */
    private void cancelOrderEvent(CarOrderInfo carOrderInfo) {

        final int reserveType = Integer.parseInt(carOrderInfo.reserveInfo.reserve_type);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switch (reserveType) {
                    //已取消（30+）
                    case 0:
                        promptDialog = new PromptDialog(mContext, getString(R.string.yes_or_no_cancel_orader), getString(R.string.free_cancel_order),
                                "确认", "取消", getString(R.string.dialogpic_nopic),new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                promptDialog.dismiss();
                                cancelCarOrder(new CommonCallBack() {
                                    @Override
                                    public void getCallBack() {
                                        promptDialog.dismiss();
                                        OrderCostActivity.startAction(mContext,carOrderNo);
                                    }
                                });
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                promptDialog.dismiss();
                            }
                        });
                        promptDialog.show();
                        break;
                    //免费取消（0-3）
                    case 1:
                        promptDialog = new PromptDialog(mContext, getString(R.string.yes_or_no_cancel_orader), getString(R.string.free_cancel_order),
                                "确认", "取消", getString(R.string.dialogpic_nopic),new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                promptDialog.dismiss();
                                cancelCarOrder(new CommonCallBack() {
                                    @Override
                                    public void getCallBack() {
                                        finish();
//                                                OrderCostActivity.startAction(mContext,carOrderNo);
                                    }
                                });
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                promptDialog.dismiss();
                            }
                        });
                        promptDialog.show();
                        break;
                    //付费取消（3-15）
                    case 2:
                        /*promptDialog = new PromptDialog(mContext, getString(R.string.yes_or_no_cancel_orader), getString(R.string.pay_cancel_order),
                                "确认", "取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                promptDialog.dismiss();
                                OrderCostActivity.startAction(mContext,carOrderNo);
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                promptDialog.dismiss();
                            }
                        });
                        promptDialog.show();*/
                        promptDialog = new PromptDialog(mContext, getString(R.string.yes_or_no_cancel_orader), getString(R.string.auto_cancel_order),
                                "确认", "取消", getString(R.string.dialogpic_nopic),new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                promptDialog.dismiss();
                                cancelCarOrder(new CommonCallBack() {
                                    @Override
                                    public void getCallBack() {
                                        promptDialog.dismiss();
                                        OrderCostActivity.startAction(mContext,carOrderNo);
                                    }
                                });
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                promptDialog.dismiss();
                            }
                        });
                        promptDialog.show();
                        break;
                }

            }
        });
    }

    /**
     * 操作车辆
     *
     * @param operator_type
     */
    private void operateCar(final String operator_type,final boolean isTakePhoto,BDLocation bdLocation) {
        String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        new LHttpLib().operatorCar(mContext,bdLocation, memberId, carOrderNo, operator_type, new BaseLHttpHandler(mContext, true, true) {
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //打开车门
                        if (operator_type.equals("1")) {
                            if (isTakePhoto){
                                operatorCarOrder("1", updateServerPhotos);
                            }else {
                                operatorCarOrder("1",null);
                            }
                        }
                    }
                });
            }
        });
    }
    /**
     * 判断用户是否在车辆旁边
     *
     * @param
     */
    private void GetMemberToCar() {
        String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        new LHttpLib().getMemberToCar(mContext, memberId, carOrderNo,String.valueOf(bdLocation.getLatitude()),String.valueOf(bdLocation.getLongitude()), new BaseLHttpHandler(mContext, true, true) {
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //开始取车拍照
                        Intent intent = new Intent(mContext, TakeCarPhotoOpenActivity.class);
                        intent.putExtra("car_no", carOrderNo);
                        intent.putExtra("longitude", String.valueOf(bdLocation.getLongitude()));
                        intent.putExtra("latitude", String.valueOf(bdLocation.getLatitude()));
                        intent.putExtra("address", String.valueOf(bdLocation.getAddrStr()));
                        intent.putExtra("Route", String.valueOf(bdLocation.getAddrStr()));
                        intent.putExtra("status", "0");
                        startActivityForResult(intent, 201);
                    }
                });
            }
        });
    }
    /**
     * @param operator_type (1-开始用车/2-取消订单/3-编辑订单)
     */
    private void operatorCarOrder(final String operator_type, List<DamageImageInfo> imageInfos) {
        new LHttpLib().operatorCarOrder(mContext, memberId, carOrderNo, operator_type, imageInfos, new BaseLHttpHandler(mContext, true, true) {
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (operator_type) {
                            case "1":
                                prompt("开车门");
                                DataLoadUtil.getCarOrderDetailOrderRun(true,mContext, carOrderNo, new CarOrderInfoCallBack() {
                                    @Override
                                    public void getCarOrderInfo(CarOrderInfo carOrderInfo) {
                                        currentCarOrderInfo = carOrderInfo;
                                    }
                                });
                                startUseCar();
                                break;
                            case "3":
                                prompt("编辑订单成功");
                                break;
                        }
                    }
                });
            }
        });
    }

    /**
     * @param
     */
    private void cancelCarOrder(final CommonCallBack commonCallBack) {
        new LHttpLib().operatorCarOrder(mContext, memberId, carOrderNo, "2", null, new BaseLHttpHandler(mContext, true, true) {
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        commonCallBack.getCallBack();
                    }
                });
            }
        });
    }

    /**
     * 开始用车
     */
    private void startUseCar() {
        //定时刷新订单运行数据
        if(Order==1){
            DataLoadUtil.getCarOrderDetailOrderRun(true,mContext, carOrderNo, new CarOrderInfoCallBack() {
                @Override
                public void getCarOrderInfo(CarOrderInfo carOrderInfo) {
                    currentCarOrderInfo = carOrderInfo;
                }
            });
        }
        operateLinear.setVisibility(View.GONE);
        cancelOrderText.setVisibility(View.GONE);
        find_car_exception.setVisibility(View.GONE);
        topBar.setText(TopBar.RIGHT_TV_BTN, "用车反馈");
        topBar.setRightOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开始取车拍照
                Intent intent = new Intent(mContext, TakePhotoFeedbackActivity.class);
                intent.putExtra("car_no", carOrderNo);
                intent.putExtra("longitude", String.valueOf(bdLocation.getLongitude()));
                intent.putExtra("latitude", String.valueOf(bdLocation.getLatitude()));
                intent.putExtra("address", String.valueOf(bdLocation.getAddrStr()));
                intent.putExtra("Route", String.valueOf(bdLocation.getAddrStr()));
                intent.putExtra("status", "1");
                startActivityForResult(intent, 202);
            }
        });
        //根据车辆类型判断是否显示自助加油按钮
        if ("1".equals(currentCarOrderInfo.carInfo.car_goup_info.car_type)) {
            selfServeText.setVisibility(View.VISIBLE);
        }
        returnCarLinear.setVisibility(View.VISIBLE);
        usingCarInfoLinear.setVisibility(View.VISIBLE);
        parkInfoLinear.setVisibility(View.GONE);
        DataLoadUtil.getCarOrderDetailOrderRun(true,mContext, carOrderNo, new CarOrderInfoCallBack() {
            @Override
            public void getCarOrderInfo(final CarOrderInfo carOrderInfo) {
                //        11	预约进行中	预约进行中	0	预约中
                //        12	预约已取消	预约已取消	1	已取消
                //        13	预约取消违约待支付	预约取消违约待支付	1	待支付
                //        14	预约取消违约已支付	预约取消违约已支付	1	已支付
                //        21	正常使用进行中	正常使用进行中	0	使用中
                //        22	正常使用完成待支付	正常使用完成待支付	1	待支付
                //        23	正常使用完成已支付	正常使用完成已支付	1	已支付
                //        31	异常使用关闭待支付	异常使用关闭待支付	1	待支付
                //        32	异常使用关闭已支付	异常使用关闭已支付	1	已支付
                //        41	后台关闭	后台关闭	1	已关闭
                //        24	正常使用完成等待中	正常使用完成等待中	1	计算中
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //订单状态是21则隐藏返回键
                        currentCarOrderInfo = carOrderInfo;
                        if ("21".equals(carOrderInfo.car_order_status_id)){
                            topBar.hideView(TopBar.LEFT_IMAGE_BTN);
                        }else {
                            topBar.showView(TopBar.LEFT_IMAGE_BTN);
                        }
                    }
                });
            }
        });
    }

    @Override
    public void finish() {
        super.finish();
        startActivity(new Intent(mContext, MainActivity.class));
    }

    /**
     * 申请还车
     */
    private void applyReturnCar() {
        //本网点还车
        final String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        final String parking_site_no = currentCarOrderInfo.parking_site_info.parking_site_no;
        if (bdLocation == null ||bdLocation.getLongitude() == 0)return;
        new LHttpLib().checkParkingSite(mContext, memberId, carOrderNo, parking_site_no, String.valueOf(bdLocation.getLongitude()),
                String.valueOf(bdLocation.getLatitude()), new BaseLHttpHandler(mContext, true, true) {
                    @Override
                    public void onSuccess(JSONStatus jsonStatus) {
                        super.onSuccess(jsonStatus);
                        final String is_in_parking_site = jsonStatus.data.optString("is_in_parking_site");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                promptDialog = new PromptDialog(mContext, getString(R.string.return_car_notice), getString(R.string.return_car_content),
                                        getString(R.string.return_car_btn_two), getString(R.string.return_car_btn_one),getString(R.string.dialogpic_nopic),new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        promptDialog.dismiss();
                                        //附近网点还车
                                        Intent intent = new Intent(mContext, ParkingSpaceActivity.class);
                                        intent.putExtra("car_order_no", carOrderNo);
                                        intent.putExtra("parking_site_no", currentCarOrderInfo.parking_site_info.parking_site_no);
                                        intent.putExtra("longitude_num", String.valueOf(bdLocation.getLongitude()));
                                        intent.putExtra("latitude_num", String.valueOf(bdLocation.getLatitude()));
                                        intent.putExtra("distance_range", currentDistanceAll);
                                        startActivityForResult(intent, 200);

                                    }
                                }, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        promptDialog.dismiss();
                                        applyReturnCar2();

                                    }
                                }, "1".equals(is_in_parking_site) ? true : false);
                                promptDialog.setCanceledOnTouchOutside(true);
                                promptDialog.show();
                            }
                        });

                    }
                });


    }
    /**
     * 申请还车
     */
    private void applyReturnCar2() {
        //本网点还车
        //parking_site_no
        final String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        final String parking_site_no = currentCarOrderInfo.parking_site_info.parking_site_no;
        if (bdLocation == null ||bdLocation.getLongitude() == 0)return;
        new LHttpLib().returnCar(mContext,carOrderNo, memberId, PreferencesUtils.getString(mContext,"Park_NO"), String.valueOf(bdLocation.getLongitude()),
                String.valueOf(bdLocation.getLatitude()), new BaseLHttpHandler(mContext, true, true) {
                    @Override
                    public void onSuccess(JSONStatus jsonStatus) {
                        super.onSuccess(jsonStatus);
                        TakePhotoReturnCarActivity.startAction(FoundCarActivity.this, carOrderNo, PreferencesUtils.getString(mContext,"Park_NO"), 001);

                    }
                    @Override
                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                        super.onFailure(t, errorNo, strMsg);
                        PreferencesUtils.putString(mContext,"Park_NO","0");
                        prompt("请重新点击申请还车");
                        //附近网点还车
                        Intent intent = new Intent(mContext, ParkingSpaceActivity.class);
                        intent.putExtra("car_order_no", carOrderNo);
                        intent.putExtra("parking_site_no", currentCarOrderInfo.parking_site_info.parking_site_no);
                        intent.putExtra("longitude_num", String.valueOf(bdLocation.getLongitude()));
                        intent.putExtra("latitude_num", String.valueOf(bdLocation.getLatitude()));
                        intent.putExtra("distance_range", currentDistanceAll);
                        startActivityForResult(intent, 200);
                    }
                });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 200 && resultCode == RESULT_OK) {
            ParkingSite parkingSite = (ParkingSite) data.getSerializableExtra("parkingSite");
            returnCarToWebsite(parkingSite);
            /*setMap(bdLocation,parkingSite.getLatitude_num(),parkingSite.getLongitude_num());
            PreferencesUtils.putString(mContext,"Park_NO",parkingSite.getParking_site_no());*/
        }
        if (requestCode == 200 && resultCode == RESULT_CANCELED) {
            if(ParkingStat==1){
                ParkingSite parkingSite = (ParkingSite) data.getSerializableExtra("parkingSite");
                //returnCarToWebsite(parkingSite);
                setMap(bdLocation,parkingSite.getLatitude_num(),parkingSite.getLongitude_num());
                PreferencesUtils.putString(mContext,"Park_NO",parkingSite.getParking_site_no());
                ParkingStat=0;}
        }
        if (requestCode == 201) {
            //车辆拍照回调
            //损伤列表信息
            // updateServerPhotos = (List<DamageImageInfo>) data.getSerializableExtra("updateServerPhotos");
            DataLoadUtil.getCarOrderDetailOrderRun(true,mContext, carOrderNo, new CarOrderInfoCallBack() {
                @Override
                public void getCarOrderInfo(CarOrderInfo carOrderInfo) {
                    currentCarOrderInfo = carOrderInfo;
                }
            });
            if( FoundCarActivity.OrderPhoto==1){
                operateCar("1",true,bdLocation);}
            PreferencesUtils.putString(mContext,"Park_NO","0");
        }
        if (requestCode == 202) {

        }
        //申请还车
        if (requestCode == 001 && resultCode == RESULT_OK) {
            finish();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    /**加载取车网点*/
    void loadGetCar() {
        addGetCarMarker();
    }
    /**
     * 加载还车网点信息
     */
    void load() {
        new LHttpLib().getReturnParkingSiteList(mContext, memberId, carOrderNo, String.valueOf(currentLatLng.longitude),
                String.valueOf(currentLatLng.latitude), String.valueOf(currentDistanceAll),new PageInfo(page, Constants.PARK_SITE_COUNT), new BaseLHttpHandler(mContext, false, true) {
                    @Override
                    public void onSuccess(JSONStatus jsonStatus) {
                        super.onSuccess(jsonStatus);
                        JSONArray jsonArray = jsonStatus.data.optJSONArray("parking_site_list");
                        isMore = jsonStatus.pageInfo.more == 1 ? true : false;
                        overlayOptionsList = new ArrayList<>();
                        parkingSiteList = new ArrayList<>();
                        parkingMarkerList = new ArrayList<>();
                        if (jsonArray != null && jsonArray.length() > 0) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                parkingSiteList.add(new ParkingSite().parse(jsonArray.optJSONObject(i)));
                            }
                            parkingMarkerList = parkingSiteList;
                        }
//                        addMarker();
                    }
                });
    }

    /**
     * 网点还车操作
     */
    private void returnCarToWebsite(ParkingSite parkingSite) {
        TakePhotoReturnCarActivity.startAction(FoundCarActivity.this, carOrderNo, parkingSite.parking_site_no, 001);
    }
    /**
     * 接受支付成功的通知信息
     * @param paymentCode
     */
    public void onEventMainThread(String paymentCode){
        switch (paymentCode){
            case "success":
                //刷新
//                cancelCarOrder(new CommonCallBack() {
//                    @Override
//                    public void getCallBack() {
                finish();
//                    }
//                });
        }
    }

    /**
     * 开启定时刷新数据任务
     */
    private  Timer timer;
    TimerTask mTimerTask;
    private void startRefreshData(){
        if(timer==null){
            timer = new Timer();
        }
        if(mTimerTask==null){
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    //获取车辆订单信息
                    DataLoadUtil.getCarOrderDetailOrderRun(false,mContext, carOrderNo, new CarOrderInfoCallBack() {
                        @Override
                        public void getCarOrderInfo(CarOrderInfo carOrderInfo) {
                            currentCarOrderInfo = carOrderInfo;
                            showDataToViewOrderRun(currentCarOrderInfo);
                        }
                    });
                    //回归到我的位置
                    if(bdLocation != null){
                        if(CarMaker!=null){
                            CarMaker.remove();
                        }
                        if(mBaiDuMap!=null){
                            mBaiDuMap.clear();
                        }
                        setMyLocationToCenter(new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude()));}
                }
            };
        }
        if(timer != null && mTimerTask != null )
            timer.schedule(mTimerTask,0, 30000);
    }

    //    private class MyThread extends Thread {
//
//        public boolean stop;
//
//        public void run() {
//            while (!stop) {
//               //获取车辆订单信息
//                DataLoadUtil.getCarOrderDetailOrderRun(false,mContext, carOrderNo, new CarOrderInfoCallBack() {
//                    @Override
//                    public void getCarOrderInfo(CarOrderInfo carOrderInfo) {
//                        currentCarOrderInfo = carOrderInfo;
//                        showDataToViewOrderRun(currentCarOrderInfo);
//                    }
//                });
//                //回归到我的位置
//                if(bdLocation != null){
//                    setMyLocationToCenter(new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude()));}
//                /*if(bdLocation != null){
//                setMyLocationToCenter(new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude()));
//                    mBaiDuMap.clear();
//                    load();}*/
//                // 通过睡眠线程来设置定时时间
//                if(currentCarOrderInfo.car_order_status_id.equals("22")){
//                  //  OrderCostActivity.startAction(mContext,carOrderNo);
//                }
//                try {
//                    Thread.sleep(30000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        };
//    };
    //----------------地图相关--------------------------------
    //弹出Dialog 选择外部地图
    private void setMap(final BDLocation bdLocation,final double La,final double Lo){
        final Dialog dia=new AlertDialog.Builder(mContext).create();

        View view=LayoutInflater.from(mContext).inflate(R.layout.dialog_map, null);

        dia.show();
        dia.getWindow().setGravity(Gravity.BOTTOM);
        dia.getWindow().setContentView(view);



        TextView tv_baidu=(TextView) view.findViewById(R.id.tv_baidu);
        TextView tv_quxiao=(TextView) view.findViewById(R.id.tv_quxiao);
        TextView tv_gaode=(TextView) view.findViewById(R.id.tv_gaode);


//调用外部百度地图

        tv_baidu.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                baidu(bdLocation);
                dia.dismiss();
            }
        });

//调用外部高德地图
        tv_gaode.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                bd09_To_Gcj02(La,Lo);
                dia.dismiss();
            }
        });

//取消对话框
        tv_quxiao.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dia.dismiss();
            }
        });
    }
    /**
     * * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换算法 * * 将 BD-09 坐标转换成GCJ-02 坐标 * * @param
     * bd_lat * @param bd_lon * @return
     */
    public  double pi = 3.1415926535897932384626;
    public  void bd09_To_Gcj02(double bd_lat, double bd_lon) {
        double x = bd_lon - 0.0065, y = bd_lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * pi);
        double gg_lon = z * Math.cos(theta);
        double gg_lat = z * Math.sin(theta);
        gaoDe(gg_lat,gg_lon);
    }
    //调用外部高德地图方法

    private void gaoDe(double La,double Lo){
        if (ViewUtil.isAvilible(mContext, "com.autonavi.minimap")) {
            try{
                Intent intent = Intent.getIntent("androidamap://navi?sourceApplication=站点&poiname=停车网点&lat="+La+"&lon="+Lo+"&dev=0");
                mContext.startActivity(intent);
            } catch (URISyntaxException e)
            {e.printStackTrace(); }
        }else{
            Toast.makeText(mContext, "您尚未安装高德地图", Toast.LENGTH_LONG).show();
            Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            mContext.startActivity(intent);
        }

    }

    private void baidu(BDLocation bdLocation){
        //起点经纬度

        LatLng sLatLng=new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
        //终点经纬度

        LatLng eLatLng=new LatLng(currentCarOrderInfo.parking_site_info.latitude_num, currentCarOrderInfo.parking_site_info.longitude_num);

        RouteParaOption para = new RouteParaOption();
        para.startName("从这里开始");
        para.startPoint(sLatLng);
        // para.endName(address);//起点位置
        para.endPoint(eLatLng);

        try {
            BaiduMapRoutePlan.openBaiduMapDrivingRoute(para, this);
            //BaiduMapNavigation.openBaiduMapNavi(para, this);
        } catch (BaiduMapAppNotSupportNaviException e) {
            e.printStackTrace();
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("您尚未安装百度地图app或app版本过低，点击确认安装？");
            builder.setTitle("提示");

            builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    OpenClientUtil.getLatestBaiduMapApp(mContext);
                    //BaiduMapNavigation.
                }
            });

            builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            builder.create().show();
        }
    }
}

